<?php

namespace App\Listener;

use App\Event\RechargeEvent;
use App\Helpers\ConfigUtil;
use App\Model\CallBase;
use App\Model\CoinLog;
use App\Model\Message;
use App\Model\PayOrder;
use App\Model\UserCoin;
use App\Model\UserFreeCall;
use App\Model\UserProfile;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;

/**
 * 首次充值监听
 * @Listener 
 */
class FirstRechargeListener implements ListenerInterface
{
    public function listen(): array
    {
        // 返回一个该监听器要监听的事件数组，可以同时监听多个事件
        return [
            //充值事件
            RechargeEvent::class,
        ];
    }

    /**
     * @param UserRegistered $event
     */
    public function process(object $event)
    {
        $userId = $event->userId;

        //天天福利券处理
        $this->freeCallProccess($userId);

        //被主播呼叫天天福利的引导奖励
        $baseCoin = $event->rechargeRmb * 10;
        $this->hostFreeCallReward($userId, $baseCoin);
    }

    /**
     * 天天福利处理
     */
    function freeCallProccess($userId = 0)
    {
        //非男性不给福利
        $profile = UserProfile::getProfile($userId);
        if ($profile->gender != 1) return;

        //当天已赠送的张数
        $freeCount = UserFreeCall::checkValid($userId, '', -2, 'count');
        //当天已经充值的笔数
        // $payCount = PayOrder::checkSuccessCount($userId, date('Y-m-d'));
        //赠送>充值次数+1次免费
        if ($freeCount >= 1) {
            log_info(__CLASS__ . "=={$userId}==SendCount:{$freeCount}");
            return false;
        }

        //当天还未充值
        $orderItem = PayOrder::checkSuccess($userId, date('Y-m-d'));
        if (!$orderItem) {
            log_info(__CLASS__ . "=={$userId}==CheckNoPay");
            return false;
        }

        $extra['pay_order_id'] = $orderItem->id;
        $freeTime = ConfigUtil::getNewFreeCallTime(true);
        UserFreeCall::addRecord($userId, $freeTime, $extra, UserFreeCall::FROM_RECHARGE);
        log_user_result($userId, "AddFreeCall:{$freeTime}");
    }

    /**
     * 被主播呼叫天天福利的引导奖励
     */
    function hostFreeCallReward($userId = 0, $rechargeCoin = 0)
    {
        //已经分过给主播充值奖励
        $rewardCount = $this->getRewardLog($userId);
        if ($rewardCount > 0) return false;
        $profile = UserProfile::getProfile($userId);
        if(!empty($profile->invite_code)) return false;

        //主播呼叫的福利话单
        $freeCall = CallBase::checkFreeCallFromHost($userId, check_dev_env() ? 3 : 120);
        if (!$freeCall) return false;

        $hostId = $freeCall->user_id;
        //主播分得充值金币的比例
        $rewardPercent = ConfigUtil::freeCallRechargeReward();
        $rewardCoin = $rechargeCoin * $rewardPercent;
        //更新收入账户
        $remainCoin = UserCoin::gainIncome($hostId, $rewardCoin);
        //账户流水
        CoinLog::addIncome(
            $hostId,
            $rewardCoin,
            CoinLog::FROM_DAILY_FREE_RECHARGE,
            $remainCoin,
            '',
            $userId
        );
        //站内信通知
        $this->pushNotice($hostId, $userId, $rewardCoin);
        log_user_result($userId, "HostId:{$hostId}==Reward:{$rewardCoin}");
    }

    /**
     * 获取天天福利的用户充值奖励
     */
    function getRewardLog($userId = 0)
    {
        $where = [
            ['op_user_id', $userId],
            ['from', CoinLog::FROM_DAILY_FREE_RECHARGE],
        ];
        return CoinLog::where($where)->count();
    }

    /**
     * 站内通知
     */
    function pushNotice($hostId = 0, $userId = 0, $rewardCoin = 0)
    {
        $profile = UserProfile::getProfile($userId);
        $rechargeTime = date('Y年m月d H:i:s');
        $msgContent = [
            'title' => '速配首充奖励到账通知！',
            'text' => "与你匹配通话过的【{$profile->nick_name}】于{$rechargeTime}充值了，恭喜你获得{$rewardCoin}金币的首充奖励！",
            'jump_info' => null,
        ];
        return Message::pushOfficial($hostId, $msgContent, Message::MSG_TYPE_TEXT);
    }
}
